package main

import (
	"flag"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	gocv "gocv.io/x/gocv"
)

var (
	processDir string
	srcFormat  string
	dstFormat  string
)

func init() {
	flag.StringVar(&processDir, "path", ".", "process convert pictures directory")
	flag.StringVar(&srcFormat, "src_format", "", "before convert format")
	flag.StringVar(&dstFormat, "dst_format", "", "before convert format")
}

func convert(beforePath, afterPath string) error {
	if beforePath == "" || afterPath == "" {
		return fmt.Errorf("path is empty")
	}

	gocv.WaitKey(0)

	return nil
}

func main() {
	flag.Parse()
	if processDir == "" || srcFormat == "" || dstFormat == "" {
		fmt.Printf("usage: process <path> <src_format> <dst_format>\n")
		flag.PrintDefaults()
		return
	}

	filenames := []string{}
	err := filepath.Walk(processDir, func(pathname string, info os.FileInfo, err error) error {
		if err != nil {
			return fmt.Errorf("visited %s error: %v", pathname, err)
		}
		if info.IsDir() || path.Ext(pathname)[1:] != srcFormat {
			return nil
		}
		filenames = append(filenames, pathname)
		return nil
	})
	if err != nil {
		fmt.Printf("walk the directory %s error: %v\n", processDir, err)
		return
	}

	for _, filename := range filenames {
		suffix := path.Ext(filename)
		suffixIndex := strings.LastIndex(filename, suffix)
		base := filename[:suffixIndex]

		beforePath := filename
		afterPath := base + "." + dstFormat
		err := convert(beforePath, afterPath)
		if err != nil {
			fmt.Printf("convert %s to %s error: %v\n", beforePath, afterPath, err)
			continue
		}
		fmt.Printf("%s -> %s\n", beforePath, afterPath)
	}
}
